$(function () {
    let goodsId = getQueryString("goodsId");
    let url = '../product/list';
    if (goodsId) {
        url += '?goodsId=' + goodsId;
    }
    $("#jqGrid").Grid({
        url: url,
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '商品', name: 'goodsName', index: 'goods_id', width: 120},
            {
                label: '商品规格',
                name: 'specificationValue',
                index: 'goods_specification_ids',
                width: 100,
                formatter: function (value, options, row) {
                    return value.replace(row.goodsName + " ", '');
                }
            },
            {label: '商品序列号', name: 'goodsSn', index: 'goods_sn', width: 80},
            {label: '商品库存', name: 'goodsNumber', index: 'goods_number', width: 80},
            {label: '零售价格(元)', name: 'retailPrice', index: 'retail_price', width: 80},
            {label: '市场价格(元)', name: 'marketPrice', index: 'market_price', width: 80}
        ]
    });

});

let vm = new Vue({
    el: '#rrapp',
    // data: {
    //
    // },
    data () {
        return {
            showList: true,
            title: null,
            product: {},
            specificationValue:"",
            list : [],
            ruleValidate: {
                name: [
                    {required: true, message: '名称不能为空', trigger: 'blur'}
                ]
            },
            q: {
                goodsName: ''
            },
            goodss: [],
            attribute: [],
            color: [], guige: [], weight: [],
            colors: [],
            guiges: [],
            weights: [],
            type: '',

            addTableTitle: [],


            list: [
                {
                    name: '颜色',
                    list: [
                        // {
                        //     goodsId: 1181002,
                        //     goodsName: "8度米酒",
                        //     id: 11,
                        //     picUrl: null,
                        //     specificationId: 2,
                        //     specificationName: "规格",
                        //     value: "6瓶装"
                        // }
                    ]
                },
                { name: '规格', list: [] },
                { name: '重量', list: [] }
            ],
            checkList: [
                { name: '颜色', list: [] },
                { name: '规格', list: [] },
                { name: '重量', list: [] }
            ],
            skuArray: [],
            skuList: [],
            dataList: [],
            uploadIndex: 0          // 上传图片序号（行号）
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.product = {};
            vm.getGoodss();
            vm.type = 'add';
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            var rowid = $("#jqGrid").jqGrid("getGridParam", "selrow");
            var rowData = jQuery("#jqGrid").jqGrid("getRowData", rowid);
            vm.specificationValue=rowData.specificationValue;xx
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.type = 'update';
            vm.checkList[1].list=[]
            vm.addTableTitle=[]
            vm.dataList = []
            vm.getInfo(id)
        },
        changeGoods: function (opt) {
            let goodsId = opt.value;
            if(!goodsId)return;

            Ajax.request({
                url: "../goods/info/" + goodsId,
                async: true,
                successCallback: function (r) {
                    if (vm.type == 'add') {
                        vm.product.goodsSn = r.goods.goodsSn;
                        vm.product.goodsNumber = r.goods.goodsNumber;
                        vm.product.retailPrice = r.goods.retailPrice;
                        vm.product.marketPrice = r.goods.marketPrice;
                    }



                    // Ajax.request({
                    //     url: "../specification/list",
                    //     async: true,
                    //     params: {limit: 1000, page: 1},
                    //     successCallback: function (r) {
                    //         // vm.colors = r.list;
                    //         console.log(r.list);
                    //     }
                    // });





                    Ajax.request({
                        url: "../goodsspecification/queryAll?goodsId=" + goodsId + "&specificationId=1",
                        async: true,
                        successCallback: function (r) {
                            // vm.colors = r.list;
                            vm.list[0].list = r.list;
                        }
                    });
                    Ajax.request({
                        url: "../goodsspecification/queryAll?goodsId=" + goodsId + "&specificationId=2",
                        async: true,
                        successCallback: function (r) {
                            // vm.guiges = r.list;
                            var reg=new RegExp('；','g')
                            if (vm.type=='update'){
                                var a = r.list.filter(item=>{
                                    return item.value==vm.specificationValue.replace(reg,"");
                                })
                                vm.list[1].list=a;
                            }else{
                                 vm.list[1].list = r.list;
                            }
                        }
                    });
                    Ajax.request({
                        url: "../goodsspecification/queryAll?goodsId=" + goodsId + "&specificationId=4",
                        async: true,
                        successCallback: function (r) {
                            // vm.weights = r.list;
                            vm.list[2].list = r.list;
                        }
                    });
                }
            });
        },
        checkChange () {
            let title = []
            vm.checkList.forEach(item=>{
                if(item.list.length > 0){
                    title.push(item.name);
                }
            });
            title.push('商品库存')
            title.push('零售价格')
            title.push('市场价格')
            title.push('图片url')
            title.push('图片上传')
            vm.addTableTitle = title;

            vm.handleClick();
        },

        handleClick() {
            // 先清空数据，保证连续点击按钮，数据不会重复
            vm.skuArray = []
            vm.skuList = []
            vm.dataList = []
            // 将选中的规格组合成一个大数组 [[1, 2], [a, b]...]
            vm.checkList.forEach(element => {
                element.list.length > 0 ? vm.skuArray.push(element.list) : ''
            })
            // 勾选了规格，才调用方法
            if (vm.skuArray.length > 0) {
                vm.getSkuData([], 0, vm.skuArray)
            } else {
                vm.$message.error('请先勾选规格')
            }

            vm.skuList.forEach(skuItem=>{
                // {
                //     goodsId: 1181002,
                //     goodsName: "8度米酒",
                //     id: 11,
                //     picUrl: null,
                //     specificationId: 2,
                //     specificationName: "规格",
                //     value: "6瓶装"
                // }
                let temp = {};
                temp['goodsSpecificationIds'] = skuItem.join('_');  // 21_9_11格式
                temp['goodsNumber'] = 0;
                temp['retailPrice'] = 0;
                temp['marketPrice'] = 0;
                temp['imgUrl'] = '';
                temp['valueNameList'] = [];
                skuItem.forEach(itemId => {
                    for(let i=0;i<vm.list.length;i++){
                        for(let j=0;j<vm.list[i].list.length;j++){
                            if(itemId == vm.list[i].list[j].id){
                                temp['valueNameList'].push(vm.list[i].list[j].value);           // 名称：如红色，蓝色
                                temp['goodsId'] = vm.list[i].list[j].goodsId;
                                temp['goodsSn'] = vm.product.goodsSn;
                                temp['goodsNumber'] = vm.product.goodsNumber;
                                temp['retailPrice'] = vm.product.retailPrice;
                                temp['marketPrice'] = vm.product.marketPrice;
                                temp['imgUrl'] = vm.product.imgUrl;
                                break;
                            }
                        }
                    }
                })
                vm.dataList.push(temp);
                vm.$forceUpdate();
            })
        },
        // 递归获取每条SKU数据
        getSkuData(skuArr = [], i, list) {
            for (let j = 0; j < list[i].length; j++) {
                if (i < list.length - 1) {
                    skuArr[i] = list[i][j]
                    vm.getSkuData(skuArr, i + 1, list) // 递归循环
                } else {
                    vm.skuList.push([...skuArr, list[i][j]]) // 扩展运算符，连接两个数组
                }
            }
        },

        saveOrUpdate: function (event) {
            debugger;
            let ids = getSelectedRows("#jqGrid");
            // let url = !ids ? '../product/save':'../product/update'
            let url = ids == null ? '../product/save':'../product/update'
            if(vm.attribute.indexOf(1) == -1)vm.color = [];
            if(vm.attribute.indexOf(2) == -1)vm.guige = [];
            if(vm.attribute.indexOf(4) == -1)vm.weight = [];
            vm.dataList.goodsSpecificationIds = vm.color + '_' + vm.guige + '_' + vm.weight;
            if(ids!=null) vm.dataList[0].id=ids[0];

            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.dataList),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });

            // debugger;
            // let ids = getSelectedRows("#jqGrid");
            // let url = !ids ? '../product/save':'../product/update'
            // // let postData = JSON.parse(JSON.stringify(vm.dataList));
            // Ajax.request({
            //     type: 'POST',
            //     url: url,
            //     contentType: 'application/json',
            //     // data: postData,
            //     params: JSON.stringify(vm.dataList),//stringify
            //     // dataType: 'JSON',
            //     successCallback: function(res) {
            //         if(res.code == 0){
            //             alert('操作成功', function (index) {
            //                 vm.reload();
            //             });
            //         }
            //     }
            // })
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../product/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },

        handleSuccessPicUrl: function (res, file, fileList) {
            vm.dataList[vm.uploadIndex].imgUrl = file.response.url;
            if(res.code == 0){
                alert('图片上传成功');
            }
        },
        changeUploadIndex(index){
            vm.uploadIndex = index;
        },

        getInfo: function (id) {
            vm.attribute = [];
            Ajax.request({
                url: "../product/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.product = r.product;
                    let goodsSpecificationIds = vm.product.goodsSpecificationIds.split("_");
                    goodsSpecificationIds.forEach((goodsSpecificationId, index) => {
                        let specificationIds = goodsSpecificationId.split(",").filter(id => !!id).map(id => Number(id));
                        if (index == 0) {
                            vm.color = specificationIds;
                            if (specificationIds.length > 0) {
                                vm.attribute.push(1);
                            }
                        } else if (index == 1) {
                            vm.guige = specificationIds;
                            if (specificationIds.length > 0) {
                                vm.attribute.push(2);
                            }
                        } else if (index == 2) {
                            vm.weight = specificationIds;
                            if (specificationIds.length > 0) {
                                vm.attribute.push(4);
                            }
                        }
                    });

                    vm.getGoodss();
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.list[1].list=[];
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'goodsName': vm.q.goodsName},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getGoodss: function () {
            Ajax.request({
                url: "../goods/queryAll/",
                async: true,
                successCallback: function (r) {
                    vm.goodss = r.list;
                }
            });
        }
    }
});